package com.rightsidetech.http.controller.userApp.store;

import com.github.pagehelper.PageInfo;
import com.rightsidetech.activity.service.ActCouponService;
import com.rightsidetech.commom.base.ResponseData;
import com.rightsidetech.commom.config.GaoDeConfig;
import com.rightsidetech.commom.enums.CodeIdEnum;
import com.rightsidetech.commom.utils.BeanValidator;
import com.rightsidetech.commom.utils.gps.MapUtils;
import com.rightsidetech.http.aspect.Log;
import com.rightsidetech.http.aspect.Token;
import com.rightsidetech.http.base.BaseController;
import com.rightsidetech.system.dtos.request.store.UserStoreReq;
import com.rightsidetech.system.dtos.response.store.StoreResp;
import com.rightsidetech.system.entity.SysAgentInfo;
import com.rightsidetech.system.service.SysAgentInfoService;
import com.rightsidetech.system.service.SysStoreInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shenyu.client.springmvc.annotation.ShenyuSpringMvcClient;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.ConstraintViolation;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

/**
 * @Package: com.rightsidetech.http.controller.userApp.store
 * @ClassName: StoreController
 * @Author: yinj
 * @CreateTime: 2021/10/29 9:39
 * @Description: 用户端门店相关
 */
@Api(tags = "门店相关api")
@RestController
@RequestMapping("/userApp/store")
@ShenyuSpringMvcClient(path = "/userApp/store/**")
@Slf4j
public class StoreController extends BaseController {

    @Resource
    private SysStoreInfoService sysStoreInfoService;
    @Resource
    private GaoDeConfig gaoDeConfig;
    @Resource
    private ActCouponService actCouponService;
    @Resource
    private SysAgentInfoService sysAgentInfoService;


    @Log
    @GetMapping("/nearest_store")
    @ApiOperation("最近的门店列表")
    public ResponseData<PageInfo<StoreResp>> nearestStore(UserStoreReq req) throws Exception {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }

        List<StoreResp> list = sysStoreInfoService.nearestStore(req);
        if (CollectionUtils.isEmpty(list)) {
            //附近没有门店 返回空数组
            return ResponseData.success(null);
        }
        for (StoreResp storeResp : list) {
            Map<String, String> aMapApi = MapUtils.getAMapApi(gaoDeConfig, storeResp.getLongitude(), storeResp.getLatitude(), req.getLongitude(), req.getLatitude());
            Long distance = StringUtils.isEmpty(aMapApi.get("distance")) ? 0L : Long.parseLong(aMapApi.get("distance"));
            storeResp.setDistance(distance);

            int count = actCouponService.selectCount(storeResp.getId(),storeResp.getAgentId());
            if (count > 0){
                storeResp.setCoupon((byte) 1);
            }else {
                storeResp.setCoupon((byte) 0);
            }

        }

        list.sort(Comparator.comparingLong(StoreResp::getDistance));
        List<StoreResp> data = getPageSizeDataForRelations(list, req.getPageSize(), req.getPageNo());
        PageInfo<StoreResp> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(req.getPageNo());
        pageInfo.setPageSize(req.getPageSize());
        pageInfo.setTotal(list.size());
        pageInfo.setList(data);

        return ResponseData.success(pageInfo);

    }

    @Log
//    @Token
    @GetMapping("/findOne")
    @ApiOperation("查询门店信息.优惠券.代理商电话")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", required = true)})
    public ResponseData<StoreResp> findOne(Long id) throws Exception {
        StoreResp resp = sysStoreInfoService.findOne(id);
        if (StringUtils.isEmpty(resp)) {
            return ResponseData.fail(CodeIdEnum.EMPTY_DATA);
        }
        if (StringUtils.isEmpty(resp.getStatus()) || resp.getStatus() == -1){
            return ResponseData.fail("门店已关闭");
        }
/*        int count = actCouponService.selectCount(resp.getId());
        if (count > 0){
            resp.setCoupon((byte) 1);
        }else {
            resp.setCoupon((byte) 0);
        }*/
//        Map<String, String> aMapApi = MapUtils.getAMapApi(gaoDeConfig, resp.getLongitude(), resp.getLatitude(), lon, lat);
//        Long distance = StringUtils.isEmpty(aMapApi.get("distance")) ? 0L : Long.parseLong(aMapApi.get("distance"));
//        resp.setDistance(distance);

        //查询代理商客服电话
        SysAgentInfo sysAgentInfo = sysAgentInfoService.findAgentInfoById(resp.getAgentId());
        if (!ObjectUtils.isEmpty(sysAgentInfo)){
            resp.setCustomerMobileNo(sysAgentInfo.getCustomerMobileNo());
        }
        return ResponseData.success(resp);
    }
    @Log
    @Token
    @GetMapping("/findStoreInfo")
    @ApiOperation("根据id获取门店信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", required = true)})
    public ResponseData<StoreResp> findStoreInfo(Long id){
        StoreResp storeResp = sysStoreInfoService.selectStoreInfoById(id);
        if (StringUtils.isEmpty(storeResp)) {
            return ResponseData.fail(CodeIdEnum.EMPTY_DATA);
        }
        if (StringUtils.isEmpty(storeResp.getStatus()) || storeResp.getStatus() == -1){
            return ResponseData.fail("门店已关闭");
        }
        return ResponseData.success(storeResp);
    }

    @Log
//    @Token
    @GetMapping("/findAgentMobileNo")
    @ApiOperation("查询代理商电话")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "代理商id", required = true)})
    public ResponseData findAgentMobileNo(Long id){

        SysAgentInfo sysAgentInfo = sysAgentInfoService.findAgentInfoById(id);
        if (!ObjectUtils.isEmpty(sysAgentInfo)){
        return ResponseData.success(sysAgentInfo.getCustomerMobileNo());
        }
        return ResponseData.fail(CodeIdEnum.NOAGENT);
    }


    @Log
    @Token
    @GetMapping("/getStoreByCode")
    @ApiOperation("扫码进入门店")
    public ResponseData<StoreResp> getStoreByCode(String storeCode) {
        return sysStoreInfoService.getStoreByCode(storeCode);
    }


    /**
     * 手动分页类
     *
     * @param datas
     * @param pageSize
     * @param pageNo
     * @param <T>
     * @return
     */
    public static <T> List<T> getPageSizeDataForRelations(List<T> datas, int pageSize, int pageNo) {
        int startNum = (pageNo - 1) * pageSize + 1;                     //起始截取数据位置
        if (startNum > datas.size()) {
            return null;
        }
        List<T> res = new ArrayList<>();
        int rum = datas.size() - startNum;
        if (rum < 0) {
            return null;
        }
        if (rum == 0) {                                               //说明正好是最后一个了
            int index = datas.size() - 1;
            res.add(datas.get(index));
            return res;
        }
        if (rum / pageSize >= 1) {                                    //剩下的数据还够1页，返回整页的数据
            for (int i = startNum; i < startNum + pageSize; i++) {          //截取从startNum开始的数据
                res.add(datas.get(i - 1));
            }
            return res;
        } else if ((rum / pageSize == 0) && rum > 0) {                 //不够一页，直接返回剩下数据
            for (int j = startNum; j <= datas.size(); j++) {
                res.add(datas.get(j - 1));
            }
            return res;
        } else {
            return null;
        }
    }


}
